//
//  PictrueBrowserViewController.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/19.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit
import SVProgressHUD

/// collection 可重用 id
private let PictrueBrowserItemReuseID = "PictrueBrowserItemReuseID"

// MARK: 图片浏览控制器
class PictrueBrowserViewController: UIViewController {
    
    /// 当前索引
    var currentIndexpath: NSIndexPath
    /// 图片地址数组
    var urls: [NSURL]
    
    // MARK:  按钮监听方法
    /// 保存图片按钮
    @objc private func clickSaveButton() {
        
        let cell = picCollectionview.visibleCells()[0] as! PhotoBrowserItem
        guard let image = cell.imgView.image else {
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)

    }
    
    /// 保存图片 方法
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        let message = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    /// 关闭按钮
    @objc private func clickCloseButton() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: 构造函数
    init (indexpath: NSIndexPath, urls: [NSURL]) {
        self.currentIndexpath = indexpath
        self.urls = urls
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 视图生命周期
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
        setupUI()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册可重用 ID
        picCollectionview.registerClass(PhotoBrowserItem.self, forCellWithReuseIdentifier: PictrueBrowserItemReuseID)
        //设置数据源对象
        picCollectionview.dataSource = self
        
        ///滚动到 选中的图片
        picCollectionview.scrollToItemAtIndexPath(currentIndexpath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }

    // MARK: 懒加载子控件
    /// 大图
    lazy var picCollectionview: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: photoBrowserCollectionViewLayout())
    /// 保存按钮
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 18, titleColor: UIColor.whiteColor(), backgroundcolor: UIColor.lightGrayColor())
    /// 关闭按钮
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 18, titleColor: UIColor.whiteColor(), backgroundcolor: UIColor.lightGrayColor())
    
    // MARK: - layout 类中类
    private class photoBrowserCollectionViewLayout: UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            super.prepareLayout()
            
            itemSize = collectionView!.bounds.size
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}

// MARK: - 设置 UI
private extension PictrueBrowserViewController {
    
    func setupUI() {
        /// 添加collectionView
        view.addSubview(picCollectionview)
        picCollectionview.frame = view.bounds
        picCollectionview.backgroundColor = UIColor.whiteColor()
        
        /// 添加保存按钮
        view.addSubview(saveButton)
        saveButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(view).offset(-28)
            make.bottom.equalTo(view).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        saveButton.addTarget(self, action: "clickSaveButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        /// 添加关闭按钮
        view.addSubview(closeButton)
        closeButton.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view).offset(8)
            make.bottom.equalTo(view).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        closeButton.addTarget(self, action: "clickCloseButton", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    
}

// MARK: - UICollectionView 数据源方法
extension PictrueBrowserViewController: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictrueBrowserItemReuseID, forIndexPath: indexPath) as! PhotoBrowserItem

        cell.imageURL = urls[indexPath.item]
        
//        cell.backgroundColor = UIColor.blackColor()
        cell.photoDelegate = self
        return cell
    }
}

// MARK: - Item 代理方法
extension PictrueBrowserViewController: PhotoBrowserItemDelegate {
    func PhotoBrowserItemDidTappedImage() {
        clickCloseButton()
    }
}

extension PictrueBrowserViewController: PhotoBrowserDismissDelegate {
    func imageViewForDismissAnimator() -> UIImageView {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let cell = picCollectionview.visibleCells()[0] as! PhotoBrowserItem
        
        iv.image = cell.imgView.image
        iv.frame = cell.zoomView.convertRect(cell.imgView.frame,
            toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return iv
    }
    
    func indexPathForDismissAnimator() -> NSIndexPath {
        let indexpath = picCollectionview.indexPathsForVisibleItems()[0]
        return indexpath
    }
}


